package com.ebt.m.proposal_v2.widget.dialog;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;

import com.ebt.m.commons.buscomponent.listview.BaseIView;
import com.ebt.m.proposal_v2.adapter.EBTMultiListDialogAdapter;
import com.ebt.m.proposal_v2.bean.InsuranceEntity;
import com.ebt.m.proposal_v2.dao.ProposalApi;
import com.ebt.m.proposal_v2.dao.request.ParamGetAttaches;
import com.ebt.m.proposal_v2.dao.response.ResponseAttach;
import com.ebt.m.proposal_v2.retrofit.OnResponseListener;
import com.ebt.m.proposal_v2.retrofit.ResponseError;
import com.ebt.m.proposal_v2.retrofit.ResponsePage;
import com.ebt.m.proposal_v2.utils.DataUtils;
import com.ebt.m.commons.utils.Logger;
import com.ebt.m.view.RecyclerViewItemDivider;

import java.util.ArrayList;
import java.util.List;

/**
 * 选择附加险
 *
 * @author archer.qi
 *         Created on 2017/5/16.
 */
public class AdditionalRiskChooseDialog extends EBTBottomDialogBase {
    public static final String Arg_exists_data = "exists_data"; // 重复数据过滤
    public static final String Arg_params = "params";

    private RecyclerView mRecyclerView;
    private EBTMultiListDialogAdapter mAdapterForMultiChoose;
    private List<ResponseAttach> mListData = new ArrayList<>();
    private ArrayList<String> mExistsIds; // 已经添加的被保人
    private ParamGetAttaches mParams;
    private boolean isEmpty;

    private onAdditionalRiskChooseListener onAdditionalRiskChooseListener;

    public static AdditionalRiskChooseDialog newInstance(ArrayList<String> existsRiskIds, ParamGetAttaches params) {
        AdditionalRiskChooseDialog frg = new AdditionalRiskChooseDialog();
        Bundle extras = new Bundle();
        extras.putStringArrayList(Arg_exists_data, existsRiskIds);
        extras.putSerializable(Arg_params, params);
        frg.setArguments(extras);
        return frg;
    }

    @Override
    public void init() {
        initArguments();
        initRecyclerView();
        initBottomBar();
        addDialogBody(mRecyclerView);
        getAdditionalRisks();
    }

    private void initBottomBar() {
        setTitle("添加附加险");
        setEmptyText("您选择的主险暂无可选的附加险");
        setEmptyImageShown(true);
        setNegativeButton("取消", v -> dismiss());
        setPositiveButton("确定", v -> {
            if (isEmpty) {
                dismiss();
            } else {
                onMultiChooseSubmit();
            }
        });
    }

    private void initRecyclerView() {
        Context mContext = getActivity();
        mRecyclerView = new RecyclerView(mContext);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.addItemDecoration(new RecyclerViewItemDivider(mContext, LinearLayoutManager.VERTICAL)
                .setAppearance(1, "#ffe2e2e2"));
    }

    private void initArguments() {
        Bundle extras = getArguments();
        if (extras != null) {
            mExistsIds = extras.getStringArrayList(Arg_exists_data);
            mParams = (ParamGetAttaches) extras.getSerializable(Arg_params);
        }
    }

    private void bindRecyclerData() {
        Activity activity = getActivity();
        if (activity != null){
            mAdapterForMultiChoose = new EBTMultiListDialogAdapter(activity, mListData);
            mRecyclerView.setAdapter(mAdapterForMultiChoose);
        }
    }

    /**
     * 过滤已经存在的数据
     *
     * @param data
     */
    private void filterExists(List<ResponseAttach> data) {
        if (mExistsIds == null || mExistsIds.size() == 0 ||
                data == null || data.size() == 0) {
            if (data != null && data.size() > 0) {
                for (ResponseAttach ra : data) {
                    if (ra != null) {
                        ra.parseOptions(); // 保险选项改为options返回，基本参数解析到变量中
                    }
                }
            }
            mListData = data;
            return;
        }
        mListData.clear();
        for (ResponseAttach ra : data) {
            if (ra != null && !mExistsIds.contains(ra.productId + "")) {
                ra.parseOptions(); // 保险选项改为options返回，基本参数解析到变量中
                mListData.add(ra);
            }
        }
    }

    /**
     * 提交附加险
     */
    private void onMultiChooseSubmit() {
        if (onAdditionalRiskChooseListener == null) {
            return;
        }
        List<InsuranceEntity> mSubmitList = null;
        if (mAdapterForMultiChoose != null) {
            /* 保存的是数据在数组中的坐标*/
            List<ResponseAttach> mCheckData = mAdapterForMultiChoose.getChecked();
            if (mCheckData != null && mCheckData.size() > 0) {
                mSubmitList = new ArrayList<>();
                for (int i = 0, length = mCheckData.size(); i < length; i++) {
                    ResponseAttach checkedAttach = mCheckData.get(i);
                    if (checkedAttach != null) {
                        InsuranceEntity entity = DataUtils.toInsuranceEntity(checkedAttach);
                        if (entity != null) {
                            mSubmitList.add(entity);
                        }
                    }
                }
            }
        }
        onAdditionalRiskChooseListener.onAdditionalProductChoose(mSubmitList);
    }

    /**
     * 请求附加险列表
     */
    public void getAdditionalRisks() {
        if (mParams == null) {
            throw new NullPointerException("params is null");
        }
        showProgress(true);
        Logger.i(mParams.toString());
        ProposalApi.getInstance(getActivity().getApplicationContext()).getAdditionalProducts(mParams, mGetAdditionalRiskResponse, (BaseIView) getActivity());
    }

    private OnResponseListener mGetAdditionalRiskResponse = new OnResponseListener<List<ResponseAttach>>() {

        @Override
        public void onSuccess(List<ResponseAttach> body, ResponsePage page) {
            if (body != null && body.size() > 0) {
                filterExists(body);
                if (mListData == null || mListData.size() == 0) {
                    showEmpty(true, false, false);
                } else {
                    bindRecyclerData();
                    showEmpty(false, false, false);
                }
            } else {
                showEmpty(true, false, false);
            }
            showProgress(false);
        }

        @Override
        public void onFailure(ResponseError error) {
            if (error != null && "-102".equals(error.code)) {
                //setEmptyText("网络开小差了，请检查您的手机是否联网");
                showEmpty(false, true, false);
            } else {
                showEmpty(false, false, true);
                //setEmptyText("您选择的主险暂无可选的附加险");
            }
            showProgress(false);
        }
    };

    @Override
    public void showEmpty(boolean empty, boolean no_net, boolean net_slow) {
        super.showEmpty(empty, no_net, net_slow);
        if (empty) {
            isEmpty = true;
            setNegativeShown(false);
        }
    }

    public void addProductChooseListener(onAdditionalRiskChooseListener listener) {
        onAdditionalRiskChooseListener = listener;
    }

    public interface onAdditionalRiskChooseListener {
        void onAdditionalProductChoose(List<InsuranceEntity> additionalRiskList);
    }

    @Override
    protected void refresh() {
        super.refresh();
        getAdditionalRisks();
    }
}
